<?php

declare(strict_types=1);

namespace app\backend\middleware;

use Closure;
use app\Request;
use think\facade\Config;
use think\Response;

/**
 * 跨域中间件
 */
class CrossDomain
{
    /**
     * 允许跨域的域名
     * @var string
     */
    protected $kaiDomain;

    /**
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $this->kaiDomain = Config::get('kaige.domain', '');
        $header = Config::get('kaige.header');

        if (!isset($header['Access-Control-Allow-Origin'])) {
            $origin = $request->header('origin');

            if ($origin && ('' == $this->kaiDomain || strpos($origin, $this->kaiDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
        }
        return $next($request)->header($header);
    }
}
